﻿using AuthCenter.API.Application.Command.Request;
using AuthCenter.Domain.Request;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using Yitter.IdGenerator;

namespace AuthCenter.API.Application.Handler.Request
{
    public class CreateRequestHandler : IRequestHandler<CreateRequestCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RequestModel> requestRepo;
        private readonly IMapper mapper;

        public CreateRequestHandler(IBaseRepository<RequestModel> requestRepo,
                                    IMapper mapper)
        {
            this.requestRepo = requestRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateRequestCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var model = mapper.Map<RequestModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateName = "";
            model.CreateDate = DateTime.Now;
            TimeSpan? timeDiff = model.EndTime - model.StartTime;
            model.TotalTime = (int)timeDiff.Value.TotalDays;
            model.TotalTime = model.TotalTime * 8;
            int r = requestRepo.AddAsync(model).Result;
            if (r > 0)
            {
                result.Message = "申请成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "申请失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
